//
//  GroupPurchaseViewController.m
//  ieGou
//
//  Created by 潮汐 on 15-1-28.
//  Copyright (c) 2015年 chaox. All rights reserved.
//

#import "GroupPurchaseViewController.h"
#import "LGClient.h"
#import "NetWorkRequest.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import <CoreLocation/CoreLocation.h>
#import "BMKLocationService.h"
#import "BMKGeocodeSearch.h"
#import "BMKLocationViewDisplayParam.h"
#import "DealCell.h"
#import "MainDealCell.h"
#import "DealDetailedList.h"

@interface GroupPurchaseViewController () <UISearchBarDelegate,BMKGeoCodeSearchDelegate, BMKLocationServiceDelegate, NetWorkRequestDelegate, UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate>
{
    bool isGeoSearch;
}
@property (nonatomic, retain) NSString *searchText;
@property (nonatomic, retain) NSString *cityLocation;
@property (nonatomic, strong) BMKGeoCodeSearch *searcher;
@property (nonatomic, strong) BMKLocationService *locService;
// 经纬度
@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, retain) CLLocation *currLocation;
@property (nonatomic, retain) CLPlacemark *placemark;

@property (nonatomic, retain) NSString *jingdu;
@property (nonatomic, retain) NSString *weidu;
@property (nonatomic, retain) NSString *urlStr;
@property (nonatomic, retain) UITableView *tableView;
@property (assign, nonatomic) NSInteger count; // 下拉加载个数
@property (nonatomic, retain) NSMutableArray *arr;

@end

@implementation GroupPurchaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationBar];
//    [self startLocation];
    [self startSystemLocation];
    [self createTableView];
    [self netRequest];
    
    
}
// 定制导航栏
- (void)setNavigationBar
{
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
        [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:95/255.0 green:207/255.0 blue:173/255.0 alpha:1];
    // 创建searchBar
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(50, 0, 160, 30)];
    searchBar.placeholder = @"输入团购信息";
    searchBar.tintColor = [UIColor blackColor];
    searchBar.delegate = self;
    searchBar.keyboardAppearance = UIKeyboardAppearanceDefault;
    searchBar.barStyle = UIBarStyleDefault;
    searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
    searchBar.showsCancelButton = YES;
 // 通过遍历 修改cancel样式
    for(id cc in [searchBar subviews])
    {
        for (id zz in [cc subviews]) {
            if([zz isKindOfClass:[UIButton class]])
            {
                UIButton *btn = (UIButton *)zz;
                [btn setTitle:@"搜索"  forState:UIControlStateNormal];
                [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }
        }
    }
    self.navigationItem.titleView = searchBar;
    self.cityLocation = @"正在定位..";
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithTitle:self.cityLocation style:UIBarButtonItemStylePlain target:self action:@selector(cityAction:)]autorelease];
    
    [searchBar release];
}
//searchBar协议方法
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    // 点击按钮 触发协议button方法
    [searchBar resignFirstResponder];
    [self doSearch:searchBar];
}
//键盘搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    [self doSearch:searchBar];
}
// 把搜索的内容传给属性, 用于拼接url进行网络请求
- (void)doSearch:(UISearchBar *)searchBar{
    self.searchText = searchBar.text;
}
-(void)cityAction:(UIBarButtonItem *)sender
{
    
}
- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}
// 开始定位
- (void)startLocation
{
    self.locService = [[BMKLocationService alloc]init];
    [self.locService startUserLocationService];
    self.locService.delegate = self;
    [self.locService release];
}
// 结束定位
- (void)stopLocation
{
    [_locService stopUserLocationService];
}

//实现相关delegate 处理位置信息更新
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"您当前位置经度 %f,纬度 %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    self.jingdu = [NSString stringWithFormat:@"%f",userLocation.location.coordinate.latitude];
    self.weidu = [NSString stringWithFormat:@"%f",userLocation.location.coordinate.longitude];
//    [self.mapView updateLocationData:userLocation];
    isGeoSearch = false;
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude};
    BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeoCodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [self.searcher reverseGeoCode:reverseGeoCodeSearchOption];
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }
    [self stopLocation];
    [reverseGeoCodeSearchOption release];
}
// 接收反向编码
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:
(BMKReverseGeoCodeResult *)result
                        errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        //      在此处理正常结果
        NSLog(@"%@=====%@", result.addressDetail.city,result.address);
        self.cityLocation = result.addressDetail.city;
    }
    else {
        NSLog(@"抱歉，未找到结果 %u", error);
    }
}
// 系统定位
- (void)startSystemLocation
{
    self.locationManager = [[CLLocationManager alloc]init];
    // 设置距离筛选器
    self.locationManager.distanceFilter = 10;
    // 设置定位精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    self.locationManager.delegate = self;
    // 开始实时定位
    [self.locationManager startUpdatingLocation];
    // 始终允许访问
    [_locationManager requestAlwaysAuthorization];
    [_locationManager release];
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    self.currLocation = [locations lastObject];
    NSLog(@"经度 = %f 纬度 = %f", self.currLocation.coordinate.latitude, self.currLocation.coordinate.longitude);
    // 位置反编码
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:self.currLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error||placemarks.count==0) {
            NSLog(@"你的地址没找到");
            NSLog(@"%@", error);
        }else {
            self.placemark=[placemarks firstObject];
            // NSLog(@"位置 %@", self.placemark.name); // 位置
            //                    NSLog(@"街道   %@", self.placemark.thoroughfare);
            //                    NSLog(@"区  %@",self.placemark.subLocality);
            self.cityLocation = self.placemark.locality;
            self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithTitle:self.cityLocation style:UIBarButtonItemStylePlain target:self action:@selector(cityAction:)]autorelease];
            NSLog(@"市   %@",self.placemark.locality);
            //    CLLocationDistance distance=[fromLocation getDistanceFrom:toLocation];
        }
    }];
    [self.locationManager stopUpdatingLocation];
    [geocoder release];
}

// 网络请求
-(void)netRequest
{
    // 生成请求url
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObjects:@[@"大连"] forKeys:@[@"city"]];
    self.urlStr = [LGClient serializeURL:@"http://api.dianping.com/v1/deal/find_deals" params:dic];
    // 数组初始化
    self.arr = [NSMutableArray array];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    NSLog(@"=====%@", self.urlStr);
    [manager GET:self.urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //        NSLog(@"JSON:%@", responseObject);
        NSMutableArray *array = [responseObject objectForKey:@"deals"];
        for (NSDictionary *Dic in array) {
            DealDetailedList *dealDetailed = [[DealDetailedList alloc]init];
            [dealDetailed setValuesForKeysWithDictionary:Dic];
            [self.arr addObject:dealDetailed];
            [dealDetailed release];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error:%@", error);
    }];
}

- (void)netWorkRequest:(NetWorkRequest *)request didFailed:(NSError *)error
{
    NSLog(@"请求失败");
}

// 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 44) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 375, 200)];
    
    for (NSInteger i = 0; i < 8; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        button.frame = CGRectMake(5+i%4 * 90, 10 + i/4 * 90, 90, 90);
        button.tag = i;
        NSString *name = [NSString stringWithFormat:@"gp%ld.png", i];
        [button setBackgroundImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [headerView addSubview:button];
    }
    
    self.tableView.tableHeaderView = headerView;
    [self.view addSubview:self.tableView];
    [_tableView release];
}

- (void)buttonAction:(UIButton *)sender
{
    
}
// 实现UITableView里面的协议
// 每区几行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }  else
        return self.arr.count;
}
// 定制cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
//        NSLog(@"%@", self.arr);
    static NSString *str = @"identifier";
    DealCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:str];
    if (cell == nil) {
        cell = [[[DealCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str]autorelease];
    }
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    return cell;
    }else
    {
    static NSString *str1 = @"Identifier";
    MainDealCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:str1];
    if (cell == nil) {
        cell = [[[MainDealCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str1]autorelease];
    }
        DealDetailedList *dD = [[DealDetailedList alloc]init];
        dD = [self.arr objectAtIndex:indexPath.row];
        cell.nameLabel.text = dD.title;
        cell.introduceLabel.text = dD.Description;
        cell.priceLabel.text = [NSString stringWithFormat:@"%g", dD.current_price];
        cell.oldPriceLabel.text = [NSString stringWithFormat:@"%g", dD.list_price];
        NSURL *url = [NSURL URLWithString:dD.image_url];
        [cell.BigImageView setImageWithURL:url];
         //nsinteger 转 nsstring
//        NSString *strd = [NSString stringWithFormat:@"%ld", dD.distance];
//        // m 转 km
//        NSInteger x = [strd integerValue];
//        NSInteger i = x / 1000;
//        NSInteger j = x % 1000 / 100;
//        float z = i + j*0.1;
//        // float 转 nsstring
//        NSString *str2 = [NSString stringWithFormat:@"%g", z];
//        NSString *newStr = [str2 stringByAppendingString:@"km"];
//        cell.distanceLabel.text = newStr;
        cell.distanceLabel.text = [NSString stringWithFormat:@"已售 %ld", dD.purchase_count];
        cell.moneyView.image = [UIImage imageNamed:@"gprenminbi"];
        cell.lineView.image = [UIImage imageNamed:@"gpline"];
        
    tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    return cell;
    }
}
// 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
//不同分区行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        DealDetailedList *deal =[self.arr objectAtIndex:indexPath.row];
        NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:13]};
        CGRect rect = [deal.description boundingRectWithSize:CGSizeMake(tableView.frame.size.width, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return rect.size.height + 105;
    }else
        return 180.f;
}
//分区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.f;
}
// 设置header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 375, 22)]autorelease];
    view.backgroundColor = [UIColor colorWithRed:247/255.0 green:247/255.0 blue:247/255.0 alpha:1];
    if (section == 0) {
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 6, 100, 18)]autorelease];
        label.text=@"为你推荐";
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor lightGrayColor];
        [view addSubview:label];
    }
    if (section == 1) {
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 6, 100, 18)]autorelease];
        label.text=@"猜你喜欢";
        label.font = [UIFont systemFontOfSize:15];
        label.textColor = [UIColor lightGrayColor];
        [view addSubview:label];
    }
    return view;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
